define(function(require){
    var main =require('/static/main.js');
    require('/static/ajaxfileupload.js');
    var m = new main();
    var sales = {
        AdvertorialId : $_GET['advertorialid'],
        islook:$_GET['islook'],
        adid :3,
        ImgSrc :'',
        chosetagList:[],
        tagList:[],
        _init:function(){
            // 初始化左边菜单

            this.bindEvent();
            this.cropperImg();
            this.simditor();
            this.datetime();
            this.ajaxUpload();
            this.getSignList();
            if(sales.AdvertorialId){
                this.getInitDataGet();
            }else{
                $(".q-cont-all").fadeIn();
            }
        },
        getInitDataGet:function(){
            $.ajax({
                type: "POST",
                url: "/promote/ad-template-get",
                data : {AdvertorialId:sales.AdvertorialId},
                dataType: "json",
                success: function (ret){
                    if(ret.IsBizSuccess){
                        if(ret.AdvertorialStatus == 100 || sales.islook){
                            $("#InputMessage").next().remove();
                            $("#InputMessage").remove();
                            $("#ShowMessage").removeClass("fl").find(".q-show-ret ").css("margin",'0 auto');
                        }
                        var data = ret.Model;
                        $("#ShowMessage .MainSrc").attr("src",data.MainSrc);
                        var Imgsrc =  data.MainSrc;
                        sales.ImgSrc = sales.GetUrlRelativePath(Imgsrc);
                        sales.setVal(data.Title,'Title');
                        sales.setVal(data.ProductName,'ProductName');
                        sales.setVal(data.ShopName,'ShopName');
                        sales.setVal(data.ShopAdd,'ShopAdd');
                        sales.setVal(data.ShopPhone,'ShopPhone');
                        $(".promote-style-call").attr("href",'tel:'+data.ShopPhone);
                        sales.setVal(data.Price,'Price');
                        sales.setVal(data.OriginalPrice,'OriginalPrice');
                        sales.setVal(data.ProductCount,'ProductCount');
                        sales.editor.setValue(data.Notice);
                        sales.setCont(data.AdContent);
                        if(data.IsUseableOnWeekend){
                            $("#InputMessage .IsUseableOnWeekend").click();
                        }
                        if(data.IsUseableOnWeekend){
                            $("#InputMessage .IsUseableOnHoliday").click();
                        }
                        //团购
                        if(data.AdMarketType == 200){
                            $(".AdMarketTypeInput .radio-inline").eq(1).find("input").click();
                            $("#ShowMessage .Price").html(data.GroupPrice);
                            $("#InputMessage .GroupPrice").val(data.GroupPrice);
                            $("#GroupEndTime").val(m.formatTimeAll2(data.GroupEndTime));
                            $("#ShowMessage .GroupEnd").html('截止日期:'+m.formatLange2( new Date(m.substrTime(data.GroupEndTime)))).show();
                            var time = sales.transferDate(m.formatTimeAll2(data.GroupEndTime));
                            sales.countTime(time);
                        }
                        //日期处理
                        $("#StartDate").val(m.formatYmd(data.UseStartDate));
                        $("#ShowMessage .StartDate").html(m.formatYmdtext(data.UseStartDate));
                        $("#EndDate").val(m.formatYmd(data.UseEndDate));
                        $("#ShowMessage .EndDate").html(m.formatYmdtext(data.UseEndDate));
                        //时间处理
                        $("#StartTime").val(data.UseStartTime);
                        $("#EndTime").val(data.UseEndTime);
                        $("#ShowMessage .StartTime").html(data.UseStartTime);
                        $("#ShowMessage .EndTime").html(data.UseEndTime);
                        $(".q-cont-all").fadeIn();

                        //tagList
                        if(ret.TagList.length > 0){
                            var tagstr = '';
                            $.each(ret.TagList,function(k,v){
                                tagstr+='<li class="chose_li"  data-id="'+v.TagId+'">'+v.TagName+'<span class="ion-close-round"></span></li>'
                            });
                            $(".tag-item").html(tagstr);
                            sales.chosetagList = ret.TagList;
                            sales.setTags();
                        }
                    }
                }
            });
        },
        getSignList:function(){
                $.ajax({
                    type: "POST",
                    url: "/customer/sign-list",
                    dataType: "json",
                    success: function (ret) {
                        var str = '';
                        if(ret.Models.length > 0){
                            $.each(ret.Models,function(k,v){
                                str+='<span class="Label_btnspan" data-id="'+v.TagId+'" data-name="'+v.TagName+'">'+v.TagName+'</span>'
                            });
                            sales.tagList = ret.Models;
                            sales.setTags();
                        }else{
                            $('.Label_btn').css({'text-align':'center'})
                            str+='暂无标签'
                        }
                        $('.Label_btn').html(str);
                    }
                });

        },
        setTags:function(){
            if(sales.tagList.length > 0 && sales.chosetagList.length > 0){
                $.each(sales.tagList,function(k,v){
                    $.each(sales.chosetagList,function(key,val){
                        if(v.TagId == val.TagId){
                            $(".Label_btn").find(".Label_btnspan").eq(k).addClass("E8ECEE")
                        }
                    })
                })
            }
        },
        bindEvent:function(){
            //销售方式
            $(".AdMarketType").change(function(){
               if($(this).val() == 200){
                   $(".GroundBuyTime").show();
                   $(".GroupEndTime").show();
                   $(".GroupPrice").closest(".form-group").show();
               }else{
                   $(".GroundBuyTime").hide();
                   $(".GroupEndTime").hide();
                   $(".GroupPrice").closest(".form-group").hide();
               }
            });

            //内容框输入
            $('.p-yl2').keyup(function (e) {
                var className = $(this).data("classname"); $("#ShowMessage ."+className).text($(this).val());
            });
            //手机号输入
            $('.ShopPhone').keyup(function (e) {
                $(".promote-style-call").attr("href",'tel:'+ $(this).val());
            });

            //价格
            $(document).on("change", ".p-yl4", function(){
                var reg = $(this).val().match(/\d+(\.\d{1,2})?/);
                var txt = '';
                if (reg != null)
                {
                    txt = reg[0];
                }
                $(this).val(txt);
                var className = $(this).data("classname");
                var pricetype = $(this).data("type");
                if(className == 'Price'){
                   var type =  $("input[name='admarkettype']:checked").val();
                    if(type == 200 && pricetype == 100){
                        return false;
                    }
                }
                $("#ShowMessage ."+className).text(txt);
            });
            //选择使用日期
            $(".isuseable").change(function(){
                var Str = '';
                var sibobj = $(this).closest(".col-md-3").siblings(".col-md-3").find("input");
                if($(this).is(":checked") && sibobj.is(":checked")){
                    Str += '(周末、法定节假日除外)';
                }else if($(this).is(":checked") &&  !sibobj.is(":checked")){
                    var type = $(this).attr("data-type");
                    if(type == 100){
                        Str +=  '(周末除外)';
                    }else{
                        Str +=  '(法定节假日除外)';
                    }
                }else if(!$(this).is(":checked") &&  sibobj.is(":checked")){
                    var type = $(this).attr("data-type");
                    if(type == 200){
                        Str +=  '(周末除外)';
                    }else{
                        Str +=  '(法定节假日除外)';
                    }
                }
                $(".IsUseable").html(Str);
            });
            //添加图片
            $(document).on("click", ".add-img", function(){
                var str  = sales.addStr('img');
                $(this).closest(".form-group").after(str[0]);
                var adid = $(this).attr("data-adid");
                $(".promote-cont"+adid).after(str[1]);
            });
            //添加文字说明
            $(document).on("click", ".add-font", function(){
                var str  = sales.addStr('font');
                $(this).closest(".form-group").after(str[0]);
                var adid = $(this).attr("data-adid");
                $(".promote-cont"+adid).after(str[1]);

            });
            //添加段落
            $(document).on("click", ".promote-addgrapeach ", function(){
                var str  = ' <div class="promote-grapeach">';
                var fontsrt = sales.addStr('font');
                var imgstr = sales.addStr('img');
                str  += fontsrt[0]+imgstr[0];
                str  += '</div>';
                $(".promote-scendcon").append(str);
                $(".promote-adcontent-item").append(fontsrt[1]+imgstr[1]);
            });
            //删除
            $(document).on("click", ".del-btn", function(){
                var adid = $(this).attr("data-adid");
                $(this).closest(".form-group").remove();
                $(".promote-cont"+adid).remove();
            });
            $(document).on("keyup", ".p-yl3", function(){
                var adid = $(this).attr("data-adid");
                $(".promote-cont"+adid).text($(this).val());
            });


            // 点击选择标签
            $(document).on('click','.Label_btn span',function(){
                if($(this).hasClass('E8ECEE')){
                    $(this).removeClass('E8ECEE')
                }else{
                    $(this).addClass('E8ECEE')
                }
            })
            //删除标签
            $(document).on('click','.chose_li',function(){
                var id = $(this).attr("data-id");
                $(".Label_btn").find(".Label_btnspan").each(function(){
                   var tagid = $(this).attr("data-id");
                    $(this).removeClass('E8ECEE');
                    if(parseInt(id) == parseInt(tagid)){
                        $(this).removeClass('E8ECEE');
                    }
                });
                $(this).remove();
            })
            // 选择完成
            $('.choseOk').click(function(){
                    var str = '';
                    $('.Label_btnspan.E8ECEE').each(function(k,v){
                        var id = $(this).data('id');
                        var name = $(this).data('name');
                        str +='<li class="chose_li"  data-id="'+id+'">'+name+'<span class="ion-close-round"></span></li>';
                    })
                $(".tag-item").html(str);
                $('#TagList').modal('hide');
            })

            //保存
            $(document).on("click", ".SaveBtn", function(){
                sales.ActivitySave(false);
            });
            //发布
            $(document).on("click", ".PublishBtn", function(){
                sales.ActivitySave(true);
            });
        },
        isactive:false,
        ActivitySave:function(IsPublish){
            if(sales.isactive){
                return false;
            }
            var ImgSrc  = sales.ImgSrc.trim();
            var ImgArray = ImgSrc.substring(0,1);
            if(ImgArray == '/'){
                sales.ImgSrc = ImgSrc.substring(1);
            }

            var JsonData = {
                AdMarketType :$("input[name='admarkettype']:checked").val(),
                MainSrc :sales.ImgSrc,
                Title :$("#InputMessage .Title").val().trim(),
                ProductName :$("#InputMessage .ProductName").val().trim(),
                ShopName :$("#InputMessage .ShopName").val().trim(),
                ShopAdd :$("#InputMessage .ShopAdd").val().trim(),
                ShopPhone :$("#InputMessage .ShopPhone").val().trim(),

                UseStartDate :$("#InputMessage #StartDate").val().trim(),
                UseEndDate :$("#InputMessage #EndDate").val().trim(),
                IsUseableOnWeekend :$("#InputMessage .IsUseableOnWeekend").is(":checked"),
                IsUseableOnHoliday :$("#InputMessage .IsUseableOnHoliday").is(":checked"),
                UseStartTime :$("#InputMessage #StartTime").val(),
                UseEndTime :$("#InputMessage #EndTime").val(),
                GroupEndTime :$("#InputMessage #GroupEndTime").val(),

                GroupPrice :$("#InputMessage .GroupPrice").val().trim(),
                Price :$("#InputMessage .Price").val().trim(),
                OriginalPrice :$("#InputMessage .OriginalPrice").val().trim(),
                ProductCount :$("#InputMessage .ProductCount").val().trim(),
                Notice :sales.editor.getValue(),
                AdContent :sales.getCont()
            }
            var alltrue = true;
            var truearrya = [];
            truearrya.push( sales.errorMessage(JsonData.MainSrc,'mainsrc','请添加商品主图'));
            truearrya.push( sales.errorMessage(JsonData.Title,'title','请添加标题'));
            truearrya.push( sales.errorMessage(JsonData.ProductName,'productname','请添加商品名称'));
            //truearrya.push( sales.errorMessage(JsonData.ShopName,'shopname','请添加商户名称'));
            truearrya.push( sales.errorMessage(JsonData.ShopAdd,'shopadd','请添加商户地址'));
            truearrya.push( sales.errorMessage(JsonData.ShopPhone,'shopphone','请添加联系方式'));
            truearrya.push(sales.errorMessage(JsonData.ProductCount,'productcount','请添加商品数量'));
            truearrya.push( sales.errorMessage(JsonData.UseStartDate,'usedate','请选择开始日期'));
            truearrya.push( sales.errorMessage(JsonData.UseEndDate,'usedate','请选择结束日期'));
            truearrya.push( sales.errorMessage(JsonData.UseStartTime,'usetime','请选择开始时间'));
            truearrya.push( sales.errorMessage(JsonData.UseEndTime,'usetime','请选择结束时间'));
            truearrya.push( sales.errorMessage(JsonData.Notice,'notice','请添加购买须知'));
            truearrya.push( sales.errorMessage(JsonData.AdContent,'adcontent','请添加详情说明'));
            truearrya.push( sales.errorMessage(JsonData.Price,'price','请添加现价'));
            var Price = (JsonData.Price*1).toFixed(2);
            if(Price <= 0){
                var html = $(".pass-msg.price").html();
                if(html.length < 1){
                    $(".pass-msg.price").html('请添加正确的价格');
                }
                truearrya.push(false);
            }
            truearrya.push( sales.errorMessage(JsonData.OriginalPrice,'price','请添加原价'));
            var OriginalPrice = (JsonData.OriginalPrice*1).toFixed(2);
            if(OriginalPrice <= 0){
                var html = $(".pass-msg.price").html();
                if(html.length < 1){
                    $(".pass-msg.price").html('请添加正确的价格');
                }
                truearrya.push(false);
            }
            if(JsonData.AdMarketType == 200){
                truearrya.push( sales.errorMessage(JsonData.GroupEndTime,'groupendtime','请选择截止时间'));
                truearrya.push( sales.errorMessage(JsonData.GroupPrice,'groupprice','请添加团购价格'));
                var GroupPrice = (JsonData.Price*1).toFixed(2);
                if(GroupPrice <= 0){
                    var html = $(".pass-msg.price").html();
                    if(html.length < 1){
                        $(".pass-msg.price").html('请添加正确的价格');
                    }
                    truearrya.push(false);
                }
            }
            $.each(truearrya,function(k,v){
                if(v == false){
                    alltrue = false;
                    return false;
                }
            });
            var tagList = [];
            $(".tag-item").find(".chose_li").each(function(){
                tagList.push($(this).attr("data-id"));
            });
            if(tagList.length > 0){
                JsonData.TagIds = tagList;
            }

            if(alltrue){
                JsonData.AdvertorialId = sales.AdvertorialId;
                $.ajax({
                    type: "POST",
                    url: "/promote/ad-market-create",
                    data :JsonData,
                    dataType: "json",
                    success: function (ret){
                        if(ret.IsBizSuccess){
                            if(IsPublish){
                                //发布
                                $.ajax({
                                    type: "POST",
                                    url: "/promote/ad-publish",
                                    data :{AdvertorialId:ret.AdvertorialId},
                                    dataType: "json",
                                    success: function (ret){
                                        sales.isactive = false;
                                        if(ret.IsBizSuccess){
                                            layer.msg("发布成功");
                                            setTimeout(function(){
                                                window.location.href = "/promote/mypromote";
                                            },1500);
                                        }else{
                                            layer.msg("发布失败");
                                        }
                                    }
                                });
                            }else{
                                sales.isactive = false;
                                layer.msg("保存成功");
                                setTimeout(function(){
                                    window.location.href = "/promote/mypromote";
                                },1500);
                            }
                        }else{
                            sales.isactive = false;
                            if(IsPublish){
                                layer.msg("发布失败");
                            }else{
                                layer.msg("保存失败");
                            }

                        }
                    }
                });
            }
        },
        setVal:function(data,classname){
            $("#ShowMessage ."+classname).text(data);
            $("#InputMessage ."+classname).val(data);
        },
        setCont:function(AdContent){
            $(".promote-adcontent-item").html(AdContent);
            var str = '<div class="promote-grapeach">';
            var i = 0;
            $(AdContent).each(function(){
                var classname = $(this).attr("class");
                classname = parseInt(classname.split("promote-cont")[1]);
                i = classname > i ?classname : i;
                if($(this).find("img").length){
                    var imgsrc = $(this).find("img").attr("src");
                    str += '<div class="form-group overflow">\
                <label class="col-md-2 control-label padleft17" style="font-weight: 500;">展示图片：</label>\
                <div class="col-md-7 promote-chosetupload">\
                        <div class="input-group">\
                            <input type="text" id="example-input2-group1" name="example-input2-group1" class="form-control fileupload"  data-adid="classname" readonly="" value="'+imgsrc+'">\
                                <span class="input-group-addon"><i class="fa ion-image"></i></span>\
                            </div>\
                        </div>\
                        <div class="col-md-3 add-promote-btnlist">\
                            <ul class="p-ul5 p-ul7">\
                                <li class="add-img"  data-adid="'+classname+'"><span class="ion-image"></span></li>\
                                <li class="add-font" data-adid="'+classname+'"><span class="fa fa-font" style="font-size: 23px;"></span></li>\
                                <li class="del-btn"  data-adid="'+classname+'"><span class="fa fa-trash-o"></span></li>\
                                <div class="clear"></div>\
                            </ul>\
                        </div>\
                    </div>';
                }else{
                    var html  = $(this).html();
                    str += '<div class="form-group overflow">\
                    <label class="col-md-2 control-label padleft17" style="font-weight: 500;">文字说明：</label>\
                    <div class="col-md-7">\
                        <textarea class="form-control p-yl3"  data-adid="' + classname + '">'+html+'</textarea>\
                    </div>\
                    <div class="col-md-3 add-promote-btnlist">\
                        <ul class="p-ul5 p-ul7">\
                            <li class="add-img" data-adid="' + classname + '"><span class="ion-image"></span></li>\
                            <li class="add-font" data-adid="' + classname + '"><span class="fa fa-font" style="font-size: 23px;"></span></li>\
                            <li class="del-btn"   data-adid="' + classname + '"><span class="fa fa-trash-o"></span></li>\
                            <div class="clear"></div>\
                        </ul>\
                    </div>\
                </div>';
                }
            });
            str  += '</div>';
            sales.adid = i+2;
            $(".promote-scendcon").html(str);

        },
        //剪切图片
        cropperImg:function(){
            var options =
            {
                imageBox: '.imageBox',
                thumbBox: '.thumbBox',
                spinner: '.spinner',
            }
            var cropper = '';
            document.querySelector('#MainSrc').addEventListener('change', function(){
                var MyTest = document.getElementById("#MainSrc");
                var _this = this;
                var reader = new FileReader();
                reader.onload = function(e) {
                    options.imgSrc = e.target.result;
                    var image = new Image();
                    image.src = e.target.result;
                    image.onload = function() {
                        if(image.width < 700 || image.height < 400){
                            layer.msg("图片尺寸必须大于700*400");
                            return false;
                        }else{
                            bytesupload(options.imgSrc);
                            return false;
                        }
                    };
                }
                reader.readAsDataURL(this.files[0]);
            })
            document.querySelector('#btnCrop').addEventListener('click', function(){
                var img = cropper.getDataURL();
                bytesupload(img);
            })

            var bytesupload = function(base){
                $.ajax({
                    type: "POST",
                    url: "/promote/get-bytes-by-image-path",
                    data : {baseImg:base},
                    dataType: "json",
                    success: function (ret){
                        if(ret.IsBizSuccess){
                            $(".MainSrc").attr("src",ret.ImgSrc);
                            sales.ImgSrc = ret.FileName;
                            $("#MainSrc").next(".input-group").find("input").val(ret.ImgSrc);
                            $("#CutImg").modal('hide');
                        }else{
                            layer.msg("图片上传失败，请重新上传！");
                        }
                    }
                });
            }
        },
        //上传图片
        ajaxUpload:function(){
            var adid = 0;
            var obj = '';
            $(document).on("click", ".fileupload", function(){
                $("#file").click();
                adid = $(this).attr("data-adid");
                obj = $(this);
            });
            //图片上传
            $("#file").on("change",function () {
                ajaxFileUpload();
            });
            function ajaxFileUpload(){
                $.ajaxFileUpload({
                    url:m.baseUrl+"/customer/edit-head",
                    secureuri: false,
                    fileElementId: 'file',
                    dataType: 'json',
                    success: function (ret) {
                        if(ret.IsBizSuccess){
                            obj.val(ret.Photo);
                            $(".promote-cont"+adid).find("img").attr('src',ret.Photo)
                        }else{
                            layer.msg(ret.ErrMsg);
                            return false;
                        }
                    }
                })
                return false;
            }
        },
        //日期
        datetime:function(){
            //初始化日期控件
            function setEndTime(enddate){
                $('#StartDate').datetimepicker('remove');
                $('#StartDate').datetimepicker({
                    format:'yyyy-mm-dd',
                    language:  'zh-CN',
                    minView: "month",
                    autoclose: 1,
                    todayHighlight: 1,
                    startView: 2,
                    forceParse: 0,
                    'startDate':new Date(),
                    'endDate':sales.transferDate(enddate)
                });
            }
            function transferTime(str){
                var newstr=str.replace(/-/g,'-');
                var newdate=new Date(newstr);
                var time=newdate.getTime();
                return time;
            }
            //结束时间戳和开始时间戳比较
            function checkTime(start,end){
                if(end <= start){
                    return true;
                }
                return false;
            }
            $('#StartDate').datetimepicker({
                format:'yyyy-mm-dd',
                language:'zh-CN',
                minView: "month",
                autoclose: true,
                'startDate':new Date()
            }).on("changeDate",function(ev){
                var transferdate = sales.transferDate($("#StartDate").val());//转时间日期
                var str =  $("#StartDate").val();
                var newstr = str.split('-');
                var datestr = newstr[0]+'年' + newstr[1]+ '月' +newstr[2]+ '日'
                $(".StartDate").html(datestr);
                var newtime = new Date();
                $('#EndDate').datetimepicker('remove');
                $('#EndDate').datetimepicker({
                    format:'yyyy-mm-dd ',
                    language:'zh-CN',
                    minView: "month",
                    autoclose:true,
                    'startDate':transferdate < newtime ? newtime :transferdate
                }).on("changeDate",function(ev){
                    var enddate=$("#EndDate").val();
                    var newstr = enddate.split('-');
                    var datestr = newstr[0]+'年' + newstr[1]+ '月' +newstr[2]+ '日'
                    $(".EndDate").html(datestr);
                    setEndTime(enddate);
                });
            });
            $('#EndDate').datetimepicker({
                format:'yyyy-mm-dd',
                language:'zh-CN',
                minView: "month",
                'startDate':new Date(),
                autoclose:true
            }).on("changeDate",function(ev){
                var enddate=$("#EndDate").val();
                var newstr = enddate.split('-');
                var datestr = newstr[0]+'年' + newstr[1]+ '月' +newstr[2]+ '日'
                $(".EndDate").html(datestr);
                $("#GroupEndTime").datetimepicker('setEndDate',enddate);
               var DateTime = $("#GroupEndTime").val();
                if(DateTime.length > 0){
                    var EndTime = $("#EndTime").val();
                    if(EndTime.length < 1){
                        EndTime = '00:00'
                    }
                    if(new Date(DateTime) > new Date(enddate+ ' ' +EndTime)){
                       var time = DateTime.split(" ")[1];
                        $("#GroupEndTime").val(enddate+ ' ' +EndTime);
                        var time = sales.transferDate($('#GroupEndTime').val());
                        sales.countTime(time);
                    }
                }
                setEndTime(enddate);
            });

            $('#StartTime').datetimepicker({
                language:'zh-CN',
                format: "hh:ii",
                startView:1,
                maxView:1,
                minuteStep:10,
                autoclose: true
            }).on("changeDate",function(ev){
                var endtime = $("#StartTime").val();
                $(".StartTime").html(endtime);
                $("#EndTime").datetimepicker('setStartDate',endtime);
            });
            $('#EndTime').datetimepicker({
                format: 'hh:ii',
                language:'zh-CN',
                startView:1,
                maxView:1,
                minuteStep:10,
                autoclose: true
            }).on("changeDate",function(ev){
                var endtime = $("#EndTime").val();
                $(".EndTime").html(endtime);
                $("#StartTime").datetimepicker('setEndDate',endtime);
                var EndDate = $("#EndDate").val();
                if(EndDate.length > 0){
                    $("#GroupEndTime").datetimepicker('setEndDate',EndDate+' '+endtime);
                }

            });

            $('#GroupEndTime').datetimepicker({
                format:'yyyy-mm-dd hh:ii',
                language:'zh-CN',
                minuteStep:10,
                startDate:new Date(),
                autoclose:true
            }).on("changeDate",function(ev){
                var time = sales.transferDate($('#GroupEndTime').val());
                sales.countTime(time);
                $(".GroupEnd").show().html("截止日期:"+ m.formatLange2(time));
            });
        },

        //文本编辑器
        editor:'',
        simditor:function(){
            sales.editor = new Simditor({textarea:$("#editor"),toolbar:false});
            sales.editor.on('valuechanged',function(){
                $("#ShowMessage .Notice").html(sales.editor.getValue());
            });
        },
        getCont:function(){
            var adContent = '';
            $(".promote-scendcon").find(".col-md-7").each(function(k){
                var str  = '';
                if($(this).find("textarea").length){
                    var value  = $(this).find("textarea").val().trim();
                    if(value.length > 1){
                        str += '<p class="promote-cont'+k+'">'+value+'</p>';
                    }
                }else if($(this).find(".fileupload").length){
                    var value  = $(this).find(".fileupload").val().trim();
                    if(value.length > 1){
                        str += '<p class="promote-cont'+k+'"><img src="'+ value +'"></p>';
                    }
                }
                adContent += str;
            });
            return adContent;
        },
        //错误处理
        errorMessage:function(str,classname,errmsg){
            if(str.length < 1){
                var html = $(".pass-msg."+classname).html();
                if(html.length < 1){
                    $(".pass-msg."+classname).html(errmsg);
                }
               return false;
            }else{
                $(".pass-msg."+classname).html("");
                return true
            }
        },
        //添加段落
        addStr:function(addtype){
            if(addtype == 'img'){
                var str = '<div class="form-group overflow">\
                <label class="col-md-2 control-label padleft17" style="font-weight: 500;">展示图片：</label>\
                <div class="col-md-7 promote-chosetupload">\
                        <div class="input-group">\
                            <input type="text" id="example-input2-group1" name="example-input2-group1" class="form-control fileupload"  data-adid="'+sales.adid+'" readonly="">\
                                <span class="input-group-addon"><i class="fa ion-image"></i></span>\
                            </div>\
                        </div>\
                        <div class="col-md-3 add-promote-btnlist">\
                            <ul class="p-ul5 p-ul7">\
                                <li class="add-img"  data-adid="'+sales.adid+'"><span class="ion-image"></span></li>\
                                <li class="add-font" data-adid="'+sales.adid+'"><span class="fa fa-font" style="font-size: 23px;"></span></li>\
                                <li class="del-btn"  data-adid="'+sales.adid+'"><span class="fa fa-trash-o"></span></li>\
                                <div class="clear"></div>\
                            </ul>\
                        </div>\
                    </div>';
                var str1 = '<p class="promote-cont'+sales.adid+'"><img src="/modules/img/default.jpg"></p>';
            }else if(addtype == 'font') {
                var str = '<div class="form-group overflow">\
                    <label class="col-md-2 control-label padleft17" style="font-weight: 500;">文字说明：</label>\
                    <div class="col-md-7">\
                        <textarea class="form-control p-yl3"  data-adid="' + sales.adid + '"></textarea>\
                    </div>\
                    <div class="col-md-3 add-promote-btnlist">\
                        <ul class="p-ul5 p-ul7">\
                            <li class="add-img" data-adid="' + sales.adid + '"><span class="ion-image"></span></li>\
                            <li class="add-font" data-adid="' + sales.adid + '"><span class="fa fa-font" style="font-size: 23px;"></span></li>\
                            <li class="del-btn"   data-adid="' + sales.adid + '"><span class="fa fa-trash-o"></span></li>\
                            <div class="clear"></div>\
                        </ul>\
                    </div>\
                </div>';
                var str1 = '<p class="promote-cont'+sales.adid+'"></p>';
            }
            sales.adid ++;
            return [str,str1];

        },
        //倒计时
        log:'',
        countTime:function(endTime){
            //倒计时
            var timesTramp =  Date.parse(endTime)/1000,timestmp = Date.parse(new Date())/1000;
            if(timesTramp  < timestmp){
                return false;
            }
            timer();
            clearInterval( sales.log );
            sales.log = setInterval(timer,1000);
            function timer(){
                timestmp = Date.parse(new Date())/1000;
                var ts =  (timesTramp - timestmp);//计算剩余的毫秒数
                var day = 0, hour = 0, minute = 0, second = 0; //时间默认值   
                day = parseInt(ts / (60 * 60 * 24));
                hour = parseInt(ts / (60 * 60)) - (day * 24);
                minute = parseInt(ts / 60) - (day * 24 * 60) - (hour * 60);
                second = parseInt(ts) - (day * 24 * 60 * 60) - (hour * 60 * 60) - (minute * 60);
                if (hour <= 9) hour = '0' + hour;
                if (minute <= 9) minute = '0' + minute;
                if (second <= 9) second = '0' + second;
                if(ts < 0){
                    $(".spread-detail-price .right").removeClass("buyBtn skips").attr("data-src",'javascript:;').addClass("gray").html("活动超时");
                    clearInterval( sales.log );
                    return false;
                }
                var str = '';
                if(day > 0){
                    str += '<span class="count-time d_hours">'+day+'</span><span style="margin-left:3px;margin-right: 3px!important;font-size: 13px;">天</span>';
                }

                str += '<span class="count-time d_hours">'+hour+'</span>\
           <span>:</span>\
           <span class="count-time d_minute">'+minute+'</span>\
           <span>:</span>\
           <span class="count-time d_second">'+second+'</span>';
                $(".count-time-wrap").html(str);
                //console.log(day,hour,minute,second);

            }
        },
        //将时间字符串转为date
        transferDate:function(data){
            var start_time = data;
            var newTime= start_time.replace(/-/g,"-");
            var transferdate = new Date(newTime);
            return transferdate;
        },
        //去除域名获取相对路径
        GetUrlRelativePath:function(url){
            var arrUrl = url.split("//");
            var length = arrUrl.length;
            if(length > 1){
                var start = arrUrl[length-1].indexOf("/");
                var relUrl = arrUrl[length-1].substring(start);//stop省略，截取从start开始到结尾的所有字符
                if(relUrl.indexOf("?") != -1){
                    relUrl = relUrl.split("?")[0];
                }
                return relUrl;
            }else{
                return url;
            }
        }
    }
    sales._init();

})